import 'package:cached_network_image/cached_network_image.dart';
import 'package:cher_flare/common/models/ly_comment_model.dart';
import 'package:cher_flare/common/models/ly_video_model.dart';
import 'package:cher_flare/modules/login/models/ly_login_info_manager.dart';
import 'package:cher_flare/routes/app_pages.dart';
import 'package:cher_flare/utils/ly_data_manager.dart';
import 'package:cher_flare/utils/size_fit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';

import '../../../common/widgets/ly_action_sheet_page.dart';
import '../../../config/url_api.dart';
import '../../../http/http_utils.dart';
import '../../../utils/app_color.dart';
import '../controllers/ly_video_home_controller.dart';

class LYVideoHomePage extends StatefulWidget {
  const LYVideoHomePage({super.key});

  @override
  State<LYVideoHomePage> createState() => _LYVideoHomePageState();
}

class _LYVideoHomePageState extends State<LYVideoHomePage> {
  final controller = Get.put(LYVideoHomeController());
  final commentTextController = TextEditingController();
  List<LYCommentModel> commentsList = [];
  FocusNode focusNode = FocusNode(canRequestFocus: true);
  bool isInputTFVisible = false;

  void _userAvatarDidClick(LyVideoModel model) {
    // if (controller.playerController?.value.isPlaying == true) {
    //   controller.playerController?.pause();
    // }
    // Get.toNamed(AppPages.userPage, arguments: {
    //   'userId': model.userId,
    //   'nickname': model.nickname,
    //   'avatar': model.avatar
    // })?.then((value) {
    //   setState(() {});
    // });
  }

  void _commentDidClick(LyVideoModel model) {
    isInputTFVisible = true;
    setState(() {});
    focusNode.requestFocus();
    // commentTextController
  }

  void _sendButtonDidClick() {
    final text = commentTextController.text;
    if (text.isEmpty) {
      return;
    }
    final user = LYLoginInfoManager.getInstance.loginModel?.userInfo;
    LYCommentModel model =
        LYCommentModel(content: text, avatar: user?.avatarThumbUrl);
    commentsList.add(model);
    Future.delayed(const Duration(seconds: 5)).then((value) {
      commentsList.remove(model);
      setState(() {});
    });
    focusNode.unfocus();
    isInputTFVisible = false;
    commentTextController.text = "";
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          "Video",
          style: TextStyle(fontSize: 24, color: AppColors.color202020),
        ),
        backgroundColor: AppColors.colorD7FFDF,
        elevation: 0,
        centerTitle: false,
        flexibleSpace: FlexibleSpaceBar(
          background: Image.asset(
            //或者Image.network
            'assets/images/navi_bg.png',
            fit: BoxFit.fill,
          ),
        ),
      ),
      resizeToAvoidBottomInset: false,
      body: Stack(
        fit: StackFit.expand,
        children: [
          _makeBodyWidget(),
          Positioned(
              left: 0,
              right: 0,
              bottom: MediaQuery.of(context).viewInsets.bottom - 49,
              height: 70,
              child: Visibility(
                  visible: isInputTFVisible, child: _makeInputWidget())),
        ],
      ),
    );
  }

  Widget _makeBodyWidget() {
    return GetBuilder(
        init: controller,
        id: 'list',
        builder: (_) {
          if (controller.videoList.isEmpty) {
            return Positioned.fill(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Image.asset(
                    'assets/images/start_your_creation_img.png',
                    width: 189,
                    height: 143,
                  ),
                  SizedBox(
                    height: 20.px,
                  ),
                  Text(
                    'Loading...',
                    style: TextStyle(
                        color: colorWithRGBA(r: 0, g: 0, b: 0, a: 0.5),
                        fontSize: 16),
                  )
                ],
              ),
            );
          }
          return Positioned.fill(
            child: PageView.builder(
              scrollDirection: Axis.vertical,
              controller: controller.pageController,
              itemBuilder: (ctx, index) {
                final model = controller.videoList[index];
                return _makeItem(model, index);
              },
              itemCount: controller.videoList.length,
              onPageChanged: (index) {
                debugPrint("==============$index===================");
                final model = controller.videoList[index];
                LYDataManager.share
                    .searchUser(model.userId ?? '')
                    .then((value) {
                  controller.currentUserModel = value;
                  setState(() {});
                });
                commentsList.clear();
                controller.createPlayer(model);
              },
            ),
          );
        });
  }

  Widget _makeComment(LyVideoModel model) {
    List<Widget> list = [];
    if (commentsList.isNotEmpty) {
      for (final model in commentsList) {
        list.add(_makeCommentItem(model));
      }
    }
    list.add(Text(
      model.title ?? '',
      style: const TextStyle(
          fontWeight: FontWeight.bold,
          fontSize: 16,
          color: AppColors.whiteColor),
    ));
    return Column(
      mainAxisAlignment: MainAxisAlignment.end,
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: list,
    );
  }

  Widget _makePlayer(LyVideoModel model) {
    if (controller.currentPayVideo?.videoPath == model.videoPath &&
        controller.playerController != null) {
      return Stack(
        children: [
          Positioned.fill(
            child: AspectRatio(
              aspectRatio: controller.playerController!.value.aspectRatio,
              child: VideoPlayer(controller.playerController!),
            ),
          ),
          Visibility(
              visible: controller.showLoading,
              child: const Center(
                child: CircularProgressIndicator(
                  color: AppColors.whiteColor,
                ),
              ))
        ],
      );
    }
    return const SizedBox.shrink();
  }

  Widget _makeItem(LyVideoModel model, index) {
    return InkWell(
      onTap: () {
        if (isInputTFVisible) {
          isInputTFVisible = false;
          setState(() {});
          return;
        }
        // if (controller.value.isPlaying) {
        //   isPause = true;
        //   controller.pause();
        // } else {
        //   controller.play();
        //   isPause = false;
        // }
        if (controller.playerController?.value.isPlaying == true) {
          controller.isPause = true;
          controller.playerController?.pause();
        } else {
          controller.isPause = false;
          controller.playerController?.play();
        }
        setState(() {});
      },
      child: Container(
        decoration: BoxDecoration(
            image: DecorationImage(
                image: AssetImage(model.cover ?? ''), fit: BoxFit.fill)),
        clipBehavior: Clip.hardEdge,
        child: Stack(
          fit: StackFit.expand,
          children: [
            _makePlayer(model),
            Positioned(
              bottom: 32,
              left: 16,
              right: 131,
              child: _makeComment(model),
            ),
            Positioned(
              bottom: 32,
              right: 0,
              width: 80,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  ClipRRect(
                      borderRadius: BorderRadius.circular(20),
                      child: InkWell(
                        onTap: () => _userAvatarDidClick(model),
                        child: CachedNetworkImage(
                          imageUrl: model.avatar ?? '',
                          width: 40,
                          height: 40,
                        ),
                      )),
                  const SizedBox(
                    height: 32,
                  ),
                  InkWell(
                    onTap: () {
                      _followIconDidClick(model);
                    },
                    child: Image.asset(
                      'assets/images/video_favour_${controller.currentUserModel?.isFriend == true ? 'h' : 'n'}.png',
                      width: 34,
                      height: 34,
                    ),
                  ),
                  const SizedBox(
                    height: 24,
                  ),
                  InkWell(
                    onTap: () {
                      model.isGreat = !(model.isGreat ?? false);
                      setState(() {});
                    },
                    child: Image.asset(
                      'assets/images/video_great_${model.isGreat == true ? 'h' : 'n'}.png',
                      width: 34,
                      height: 34,
                    ),
                  ),
                  const SizedBox(
                    height: 24,
                  ),
                  InkWell(
                    onTap: () => _commentDidClick(model),
                    child: Image.asset(
                      'assets/images/video_comment_icon.png',
                      width: 34,
                      height: 34,
                    ),
                  ),
                ],
              ),
            ),
            Visibility(
              visible: controller.isPause,
              child: const Center(
                child: Icon(
                  Icons.play_circle_rounded,
                  weight: 30,
                  size: 50,
                  color: AppColors.whiteColor,
                ),
              ),
            ),
            Positioned(
                top: 20,
                right: 20,
                child: InkWell(
                  onTap: () => _moreButtonDidClick(model, index),
                  child: Image.asset(
                    'assets/images/more_icon.png',
                    width: 30,
                    height: 30,
                  ),
                ))
          ],
        ),
      ),
    );
  }

  Widget _makeCommentItem(LYCommentModel model) {
    return Container(
      height: 40,
      margin: const EdgeInsets.only(top: 12, bottom: 12),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [AppColors.blackColor, colorWithRGBA(r: 0, g: 0, b: 0, a: 0)],
        ),
        borderRadius: BorderRadius.circular(20),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const SizedBox(
            width: 4,
          ),
          ClipRRect(
              borderRadius: BorderRadius.circular(16),
              child: CachedNetworkImage(
                imageUrl: model.avatar ?? '',
                width: 32,
                height: 32,
              )),
          const SizedBox(
            width: 8,
          ),
          Text(
            model.content ?? '',
            style: const TextStyle(fontSize: 15, color: AppColors.whiteColor),
          ),
        ],
      ),
    );
  }

  Widget _makeInputWidget() {
    return Container(
      padding: const EdgeInsets.only(left: 20, right: 20),
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        color: AppColors.whiteColor,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            child: _makeTextFieldWidget(),
          ),
          InkWell(
            onTap: () => _sendButtonDidClick(),
            child: Container(
              alignment: Alignment.center,
              width: 63,
              height: 32,
              decoration: BoxDecoration(
                  gradient: const LinearGradient(
                      colors: [AppColors.colorCCFF78, AppColors.color78FF85]),
                  borderRadius: BorderRadius.circular(16)),
              child: const Text(
                'Send',
                style: TextStyle(color: AppColors.color404040, fontSize: 16),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _makeTextFieldWidget() {
    return Container(
      margin: const EdgeInsets.only(right: 24),
      height: 40,
      width: double.infinity,
      alignment: Alignment.centerLeft,
      // padding: const EdgeInsets.only(top: 12, bottom: 12, right: 12),
      decoration: BoxDecoration(
        color: AppColors.colorF2F2F2,
        borderRadius: BorderRadius.circular(15),
      ),
      child: TextField(
        focusNode: focusNode,
        textAlign: TextAlign.start,
        controller: commentTextController,
        style: const TextStyle(fontSize: 15, color: AppColors.color202020),
        decoration: InputDecoration(
          contentPadding: const EdgeInsets.only(
            left: 12,
          ),
          hintText: "Enter your ideas...",
          hintStyle: TextStyle(
              fontSize: 10, color: colorWithRGBA(r: 0, g: 0, b: 0, a: 0.3)),
          enabledBorder: InputBorder.none,
          disabledBorder: InputBorder.none,
          focusedBorder: InputBorder.none,
          border: InputBorder.none,
          filled: true,
          fillColor: AppColors.colorF2F2F2,
          isDense: true,
          isCollapsed: true,
        ),
      ),
    );
  }

  void _followIconDidClick(LyVideoModel model) async {
    EasyLoading.show();
    final userId = model.userId;
    if (controller.currentUserModel?.userId != model.userId && userId != null) {
      controller.currentUserModel =
          await LYDataManager.share.searchUser(userId);
    }
    if (controller.currentUserModel?.isFriend == true) {
      final response = await HttpUtils.getInstance
          .post(URLApi.unfriend, data: {'followUserId': userId});
      controller.currentUserModel?.isFriend = false;
      EasyLoading.showToast('Unfollow successfully');
    } else {
      final response = await HttpUtils.getInstance
          .post(URLApi.addFriend, data: {'followUserId': userId});
      controller.currentUserModel?.isFriend = true;
      EasyLoading.showToast('Follow successfully.');
    }
    LYDataManager.share.updateUserInfo();
    setState(() {});
    EasyLoading.dismiss();
  }

  void _moreButtonDidClick(LyVideoModel model, int index) {
    final title =
        controller.currentUserModel?.isFriend == true ? "Unfollow" : "Follow";
    final sheet = LYActionSheetPage(
      titles: [title, 'Block', 'Report'],
      onTap: (type) {
        if (type == 0) {
          _followDidClick(model);
        } else if (type == 1) {
          _blockDidClick(model, index);
        } else if (type == 2) {
          _reportDidClick(model);
        }
      },
    );
    Get.dialog(sheet, useSafeArea: false);
  }

  void _followDidClick(LyVideoModel model) async {
    EasyLoading.show(maskType: EasyLoadingMaskType.black);
    final userId = model.userId;
    if (controller.currentUserModel?.userId != model.userId && userId != null) {
      controller.currentUserModel =
          await LYDataManager.share.searchUser(userId);
    }
    if (controller.currentUserModel?.isFriend == true) {
      final response = await HttpUtils.getInstance
          .post(URLApi.unfriend, data: {'followUserId': model.userId});
      controller.currentUserModel?.isFriend = false;
      EasyLoading.showToast('Unfollow successfully');
    } else {
      final response = await HttpUtils.getInstance
          .post(URLApi.addFriend, data: {'followUserId': model.userId});
      controller.currentUserModel?.isFriend = true;
      EasyLoading.showToast('Follow successfully.');
    }
    LYDataManager.share.updateUserInfo();
    EasyLoading.dismiss();
    setState(() {});
  }

  void _blockDidClick(LyVideoModel model, int index) async {
    EasyLoading.show(maskType: EasyLoadingMaskType.black);
    if (controller.playerController != null &&
        controller.playerController?.value.isPlaying == true) {
      controller.playerController?.pause();
      controller.playerController?.dispose();
    }
    await LYDataManager.share.blackUser(model.userId);
    EasyLoading.showToast("Blocked successfully");
    controller.currentUserModel?.isFriend = false;
    controller.videoList = LYDataManager.share.videosList
        .where((element) => element.isBlack != true)
        .toList();
    if (controller.videoList.length > index) {
      final m = controller.videoList[index];
      controller.pageController.jumpToPage(index);
      controller.createPlayer(m);
    } else {
      if (controller.videoList.isNotEmpty) {
        controller.pageController.jumpToPage(index);
        controller.createPlayer(controller.videoList.last);
      }
    }
    setState(() {});
    EasyLoading.dismiss();
  }

  void _reportDidClick(LyVideoModel model) {
    final titles = [
      'Pornographic',
      'False gender',
      'Fraud',
      'Political sensitive',
      'Other'
    ];
    final sheet = LYActionSheetPage(
      titles: titles,
      onTap: (index) async {
        await _submitReport(titles[index], "Report", model.userId);
        EasyLoading.showToast('Report Successfully');
      },
    );
    Get.dialog(sheet, useSafeArea: false);
  }

  Future<void> _submitReport(String complainSub, String complainCategory,
      String? broadcasterId) async {
    EasyLoading.show();
    Map<String, String> parameters = {
      'broadcasterId': broadcasterId ?? '',
      'complainSub': complainSub,
      'complainCategory': complainCategory
    };
    final response = await HttpUtils.getInstance
        .post(URLApi.insertBlockRecord, data: parameters);
    EasyLoading.dismiss();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
    debugPrint('================dispose=====================');
  }
}
